

package VisAVisTab;


import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.rdf.model.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;

import java.sql.*;

import java.util.*;

import edu.stanford.smi.protege.model.*;
import edu.stanford.smi.protege.util.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;


///////////////////////////////////////////////////////////////////////////////
// MySQLPanel

// MySQLPanel class encapsulates the GUI components that let the user
// connect to a data source and see the tables stored there

class MySQLPanel extends JPanel
        implements ActionListener, TreeSelectionListener, ItemListener,DragSourceListener, DragGestureListener,DropTargetListener {
    
    
    
    public MySQLPanel(OntologyPanel ontPanel) {
        
        
        
        // initialize
        this.ontPanel=ontPanel;
        queryPanel= new QueryPanelMySQL(this,ontPanel);
        
        tables = new Vector();
        
        setLayout(new BorderLayout());
        
        JPanel pNorth = new JPanel(new BorderLayout());
        
        DropTarget dropTarget1=new DropTarget(txtHostIP,this);
        DropTarget dropTarget2=new DropTarget(txtPW,this);
        DropTarget dropTarget3=new DropTarget(txtUserID,this);
        DropTarget dropTarget5=new DropTarget(txtPort,this);
        
        
        GridLayout centerLayout = new GridLayout(1,3);
        centerLayout.setHgap(10);
        JPanel pCenter = new JPanel(centerLayout);
        JPanel p2 = new JPanel(new GridLayout(2,1));
        p2.add(new JLabel("Host IP", JLabel.LEFT));
        p2.add(txtHostIP);
        p2.add(new JLabel("Login", JLabel.LEFT));
        p2.add(txtUserID);
        pCenter.add(p2);
        
        JPanel p3 = new JPanel(new GridLayout(2,1));
        p3.add(new JLabel("Port"));
        p3.add(txtPort);
        p3.add(new JLabel("Password"));
        p3.add(txtPW);
        pCenter.add(p3);
        
        JPanel p4 = new JPanel();
        btnConnect.setMnemonic('C');
        btnConnect.addActionListener(this);
        p4.add(btnConnect);
        pCenter.add(p4);
        pNorth.add(pCenter,BorderLayout.CENTER);
        
        JPanel p5 = new JPanel(new FlowLayout());
        p5.add(new JLabel("Choose Database",JLabel.LEFT));
        cmbDB = new JComboBox();
        cmbDB.setEditable(false);
        p5.add(cmbDB);
        btnGo.setMnemonic('G');
        btnGo.addActionListener(this);
        p5.add(btnGo);
        pNorth.add(p5,BorderLayout.SOUTH);
        add(pNorth,BorderLayout.NORTH);
        
        
        GridBagLayout gridbag=new GridBagLayout();
        GridBagConstraints gbc=new GridBagConstraints();
        JPanel pSouth=new JPanel(gridbag);
        
        JPanel p6 = new JPanel(new BorderLayout());
        JPanel tableTypesPanel = new JPanel(new FlowLayout());
        allCheckBox = new JCheckBox("All");
        allCheckBox.setMnemonic('l');
        allCheckBox.addItemListener(this);
        tableTypesPanel.add(allCheckBox);
        sysCheckBox = new JCheckBox("System Table");
        sysCheckBox.setMnemonic('y');
        sysCheckBox.addItemListener(this);
        tableTypesPanel.add(sysCheckBox);
        tableCheckBox = new JCheckBox("Table");
        tableCheckBox.setMnemonic('t');
        tableCheckBox.addItemListener(this);
        tableTypesPanel.add(tableCheckBox);
        viewCheckBox = new JCheckBox("View");
        viewCheckBox.setMnemonic('V');
        viewCheckBox.addItemListener(this);
        tableTypesPanel.add(viewCheckBox);
        
        
        otherCheckBox = new JCheckBox("Other");
        otherCheckBox.setMnemonic('O');
        otherCheckBox.addItemListener(this);
        tableTypesPanel.add(otherCheckBox);
        p6.add(new LabeledComponent("Data Tables",tableTypesPanel,false),BorderLayout.NORTH);
        treeTables.setCellRenderer(new DBTreeCellRenderer());
        treeTables.setEditable(false);
        treeTables.setRootVisible(false);
        treeTables.setShowsRootHandles(true);
        treeTables.putClientProperty("JTree.lineStyle", "Angled");
        treeTables.addTreeSelectionListener(this);
        JPanel p7=new JPanel(new GridLayout(1,2));
        JScrollPane scrollPane = new JScrollPane(treeTables);
        scrollPane.setToolTipText("Drag a table or a column and drop it to the appropriate field to the right");
        
        scrollPane.setPreferredSize(new Dimension(250, 200));
        dragSource.addDragSourceListener(this);
        dragSource.createDefaultDragGestureRecognizer( treeTables, DnDConstants.ACTION_MOVE, this);
        
        p6.add(scrollPane,BorderLayout.CENTER);
        p7.add(p6);
        p7.add(queryPanel);
        
        ontPanel.buildConstraints(gbc,0,0,1,1,100,80,GridBagConstraints.BOTH);
        gridbag.setConstraints(p7,gbc);
        pSouth.add(p7);
        
        previewPanel = new DataPreviewPanel();
        
        ontPanel.buildConstraints(gbc,0,1,1,1,100,20,GridBagConstraints.BOTH);
        gridbag.setConstraints(previewPanel,gbc);
        pSouth.add(previewPanel);
        
        /*JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        split.setTopComponent(p7);
        split.setBottomComponent(previewPanel);*/
        //split.setDividerLocation(0.1d);
        
        
        //add(split,BorderLayout.CENTER);
        add(pSouth,BorderLayout.CENTER);
        connected = false;
        setConnectedGUI(false);
        
    }
    
    // Handle action events
    
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        
        //if button "Connect" is pressed
        if (source == btnConnect) {
            
            // reset data and GUI components
            queryPanel.tablesVector.removeAllElements();
            queryPanel.tableList.setListData(queryPanel.tablesVector);
            queryPanel.fieldsVector.removeAllElements();
            queryPanel.fieldInfoVector.removeAllElements();
            queryPanel.fieldList.setListData(queryPanel.fieldsVector);
            queryPanel.criteriaVector.removeAllElements();
            while (queryPanel.dm.getRowCount()!=0) queryPanel.dm.removeRow(0);
            
            previewPanel.deleteTable();
            tables.removeAllElements();
            rootNode = new DefaultMutableTreeNode(new TreeNodeInfo("Data Source",TreeNodeInfo.OTHER));
            treeModel = new DefaultTreeModel(rootNode);
            treeTables.setModel(treeModel);
            cmbDB.removeAllItems();
            
            setConnectedGUI(false);
            
         
            //setup the connection
            String strURL="";
            try{
                strDriver="org.gjt.mm.mysql.Driver";
                strURL = "jdbc:mysql://"+txtHostIP.getText()+":"+txtPort.getText()+"/";
                
                // load the JDBC driver
                Class.forName(strDriver);
                
                con = DriverManager.getConnection(strURL,
                        txtUserID.getText(), new String(txtPW.getPassword()));
                if (connectInfo == null)
                    connectInfo = new ConnectInfo(strDriver,strURL,txtUserID.getText(),new String(txtPW.getPassword()),"MySQL");
                else
                    connectInfo.set(strDriver,strURL,txtUserID.getText(),new String(txtPW.getPassword()),"MySQL");
                
                dsInfo = new DataSourceInfo(connectInfo);
                
                //fill the JComboBox containing the MySQL databases with the ones referring to the new connection
                ResultSet resDB = getMySQLDB(con);
                while (resDB.next()){
                    cmbDB.addItem(resDB.getString(1));
                }
                
                
            } catch (SQLException ex) {
                Global.defaultSQLExceptionHandler(JOptionPane.getFrameForComponent(this),ex);
            } catch (Exception ex) {
            }
        }
        //if button "Go" is pressed
        else if (source==btnGo){
            
            // reset data and GUI components
            queryPanel.tablesVector.removeAllElements();
            queryPanel.tableList.setListData(queryPanel.tablesVector);
            queryPanel.fieldsVector.removeAllElements();
            queryPanel.fieldInfoVector.removeAllElements();
            queryPanel.fieldList.setListData(queryPanel.fieldsVector);
            queryPanel.criteriaVector.removeAllElements();
            while (queryPanel.dm.getRowCount()!=0) queryPanel.dm.removeRow(0);
            
          
            
            //reset the data preview panel as well as the tree of the database
            previewPanel.deleteTable();
            tables.removeAllElements();
            rootNode = new DefaultMutableTreeNode(new TreeNodeInfo("Data Source",TreeNodeInfo.OTHER));
            treeModel = new DefaultTreeModel(rootNode);
            treeTables.setModel(treeModel);
            setConnectedGUI(false);
            
            databaseSelected = (String)cmbDB.getSelectedItem();
            
            try{
                if (databaseSelected!=null){
                    con = DriverManager.getConnection(connectInfo.m_DSN,connectInfo.m_UID,connectInfo.m_PWD);
                    DatabaseMetaData dbMetaData = con.getMetaData();
                    
                    
                    // Obtain all the available table types from the data source
                    ResultSet rs = dbMetaData.getTableTypes();
                    Vector tableTypesVector = new Vector();
                    boolean more = rs.next();
                    while (more) {
                        String type = rs.getString("TABLE_TYPE");
                        tableTypesVector.addElement(type);
                        more = rs.next();
                    }
                    rs.close();
                    
                    int numTypes = tableTypesVector.size();
                    String[] tableTypes = new String[numTypes];
                    for (int i = 0; i < numTypes; i++)
                        tableTypes[i] = (String)tableTypesVector.get(i);
                    
                    // Set up the data tables tree
                    
                    
                    ResultSet rsTables = dbMetaData.getTables(databaseSelected,null,null,tableTypes);
                    boolean bMore = rsTables.next();
                    while (bMore) {
                        
                        String strTableName = rsTables.getString("TABLE_NAME");
                        
                        
                        String tableTypeStr = rsTables.getString("TABLE_TYPE");
                        int tableType;
                        if (tableTypeStr.compareToIgnoreCase("SYSTEM TABLE") == 0)
                            tableType = TreeNodeInfo.TABLE_SYSTEM;
                        else if (tableTypeStr.compareToIgnoreCase("TABLE") == 0)
                            tableType = TreeNodeInfo.TABLE;
                        else if (tableTypeStr.compareToIgnoreCase("VIEW") == 0)
                            tableType = TreeNodeInfo.TABLE_VIEW;
                        else
                            tableType = TreeNodeInfo.TABLE_OTHER;
                        
                        // Get primary keys
                        if (dsInfo.m_supportsCoreSQLGrammar) {
                            rs = dbMetaData.getPrimaryKeys(databaseSelected,null,strTableName);
                            more = rs.next();
                            while (more) {
                                FieldInfo primary= new FieldInfo();
                                primary.fieldName=rs.getString("COLUMN_NAME");
                                primary.fieldParent=strTableName;
                                primaryKeys.add(primary);
                                more = rs.next();
                            }
                            rs.close();
                        }
                        
                        //add the table to the tree
                        TreeNodeInfo nodeInfo = new TreeNodeInfo(strTableName,tableType);
                        DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(nodeInfo);
                        treeModel.insertNodeInto(childNode, rootNode, rootNode.getChildCount());
                        treeTables.scrollPathToVisible(new TreePath(childNode.getPath()));
                        ResultSet rsColumns = dbMetaData.getColumns(databaseSelected,null,strTableName,null);
                        
                        //determine the data types of the columns of each table
                        boolean bMore2 = rsColumns.next();
                        while (bMore2) {
                            String strColumnName = rsColumns.getString("COLUMN_NAME");
                            
                            
                            String strTypeName = rsColumns.getString("TYPE_NAME");
                            int sqlType = rsColumns.getShort("DATA_TYPE");
                            ValueType protegeType = Global.getSQLProtegeType(sqlType);
                            String nodeText = strColumnName+" ("+strTypeName+" --> "+protegeType.toString()+")";
                            
                            // Determine whether this column is a primary key
                            int colType = TreeNodeInfo.COLUMN;
                            for (int i = 0; i < primaryKeys.size(); i++) {
                                
                                String key = ((FieldInfo)primaryKeys.elementAt(i)).fieldName;
                                String keyTable = ((FieldInfo)primaryKeys.elementAt(i)).fieldParent;
                                if ((key.compareToIgnoreCase(strColumnName) == 0)&&(keyTable.compareToIgnoreCase(strTableName) == 0)) {
                                    colType = TreeNodeInfo.COLUMN_PK;
                                    break;
                                }
                                
                            }
                            
                            //add each column to the tree under the table it belongs
                            TreeNodeInfo nodeInfo2 = new TreeNodeInfo(nodeText,colType);
                            DefaultMutableTreeNode childColumnNode = new DefaultMutableTreeNode(nodeInfo2);
                            treeModel.insertNodeInto(childColumnNode, childNode, childNode.getChildCount());
                            
                            bMore2 = rsColumns.next();
                        }
                        rsColumns.close();
                        
                        tables.add(nodeInfo);
                        
                        bMore = rsTables.next();
                    }
                    
                    rsTables.close();
                    
                    // Set the table type check boxes according to the types
                    // available in the data source
                    if (tables.size() == 0)
                        JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(this),"No table found in this data source.",Global.tabName,JOptionPane.INFORMATION_MESSAGE);
                    else {
                        setConnectedGUI(true);
                        connected = false;
                        allCheckBox.setEnabled(false);
                        sysCheckBox.setEnabled(false);
                        tableCheckBox.setEnabled(false);
                        viewCheckBox.setEnabled(false);
                        otherCheckBox.setEnabled(false);
                        for (int i = 0; i < tableTypes.length; i++) {
                            if (tableTypes[i].compareToIgnoreCase("SYSTEM TABLE") == 0) {
                                sysCheckBox.setEnabled(true);
                                sysCheckBox.setSelected(true);
                            } else if (tableTypes[i].compareToIgnoreCase("TABLE") == 0) {
                                tableCheckBox.setEnabled(true);
                                tableCheckBox.setSelected(true);
                            } else if (tableTypes[i].compareToIgnoreCase("VIEW") == 0) {
                                viewCheckBox.setEnabled(true);
                                viewCheckBox.setSelected(true);
                            } else {
                                otherCheckBox.setEnabled(true);
                                otherCheckBox.setSelected(true);
                            }
                        }
                        allCheckBox.setEnabled(true);
                        allCheckBox.setSelected(true);
                        connected = true;
                    }
                }
            } catch (SQLException ex) {
                Global.defaultSQLExceptionHandler(JOptionPane.getFrameForComponent(this),ex);
                
            } catch (Exception ex) {
            }
        }
        
        
        
    }
    
    // Handle the state changes in the table type check boxes;
    // modify the table tree to show the appropriate tables
    
    public void itemStateChanged(ItemEvent e) {
        if (connected) {
            Object item = e.getItem();
            int newState = e.getStateChange();
            if (item == allCheckBox) {
                if (newState == ItemEvent.SELECTED) {
                    sysCheckBox.setSelected(true);
                    tableCheckBox.setSelected(true);
                    viewCheckBox.setSelected(true);
                    otherCheckBox.setSelected(true);
                }
            } else if (item == sysCheckBox) {
                if (newState == ItemEvent.DESELECTED) {
                    allCheckBox.setSelected(false);
                }
            } else if (item == tableCheckBox) {
                if (newState == ItemEvent.DESELECTED) {
                    allCheckBox.setSelected(false);
                }
            } else if (item == viewCheckBox) {
                if (newState == ItemEvent.DESELECTED) {
                    allCheckBox.setSelected(false);
                }
            } else if (item == otherCheckBox) {
                if (newState == ItemEvent.DESELECTED) {
                    allCheckBox.setSelected(false);
                }
            }
            
            Vector selectTypes = new Vector();
            if (sysCheckBox.isSelected())
                selectTypes.addElement("SYSTEM TABLE");
            if (tableCheckBox.isSelected())
                selectTypes.addElement("TABLE");
            if (viewCheckBox.isSelected())
                selectTypes.addElement("VIEW");
            if (otherCheckBox.isSelected()) {
                selectTypes.addElement("GLOBAL TEMPORARY");
                selectTypes.addElement("LOCAL TEMPORARY");
                selectTypes.addElement("ALIAS");
                selectTypes.addElement("SYNONYM");
            }
            
            int numTypes = selectTypes.size();
            String[] selectTableTypes = new String[numTypes];
            for (int i = 0; i < numTypes; i++)
                selectTableTypes[i] = (String)selectTypes.get(i);
            
            selectTableTypesForView(selectTableTypes);
        }
    }
    
    
    //implements the needed methods for interfaces used to handle Drag N Drop actions
    
    public void dragDropEnd(DragSourceDropEvent event) {
    }
    
    
    public void dragExit(DragSourceEvent event) {
        //System.out.println( "dragExit");
        
    }
    
    
    public void dropActionChanged( DragSourceDragEvent event) {
        //System.out.println( "dropActionChanged");
    }
    
    public void dragOver(DragSourceDragEvent event) {
        //System.out.println( "dragOver");
        
    }
    
    public void dragEnter(DragSourceDragEvent event) {
        //System.out.println( " dragEnter");
    }
    
    
    public void dragGestureRecognized( DragGestureEvent event) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)treeTables.getLastSelectedPathComponent();
        if (node == null)
            return;
        Object selected = node.getUserObject();
        if ( selected != null ){
            StringSelection text = new StringSelection( selected.toString());
            
            // as the name suggests, starts the dragging
            dragSource.startDrag(event, DragSource.DefaultMoveDrop, text, this);
        } else {
            System.out.println( "nothing was selected");
        }
    }
    public void drop(DropTargetDropEvent event) {
        //reject drop actions for the upper connection fields
        if ((event.getDropTargetContext().getComponent()==txtUserID)||
                (event.getDropTargetContext().getComponent()==txtPW)||(event.getDropTargetContext().getComponent()==txtPort)||
                (event.getDropTargetContext().getComponent()==txtHostIP)){
            event.rejectDrop();
        }
    }
    
    public void dragExit(DropTargetEvent event) {
        //System.out.println( "dragExit");
    }
    
    public void dropActionChanged( DropTargetDragEvent event ) {
    }
    
    public void dragOver(DropTargetDragEvent event) {
        // System.out.println( "dragOver");
    }
    public void dragEnter(DropTargetDragEvent event) {
        
        //System.out.println( "dragEnter");
        //event.acceptDrag (DnDConstants.ACTION_MOVE);
    }
    
    //Find the list of databases that are written in MySQL
    
    public ResultSet getMySQLDB(Connection con) throws SQLException{
        
        String strQuery="SHOW DATABASES";
        PreparedStatement myStmt;
        ResultSet ret = null;
        
        try {
            myStmt = con.prepareStatement(strQuery);
            ret = myStmt.executeQuery(strQuery);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return ret;
    }
    
    
    // Take a list of table types and modify the tree to show all the
    // tables of those types.
    
    private void selectTableTypesForView(String[] tableTypes) {
        
        // reset data and GUI components
        previewPanel.deleteTable();
        tables.removeAllElements();
        rootNode = new DefaultMutableTreeNode(new TreeNodeInfo("Data Source",TreeNodeInfo.OTHER));
        treeModel = new DefaultTreeModel(rootNode);
        treeTables.setModel(treeModel);
        
        try {
            // load the JDBC driver
            Class.forName(strDriver);
            
            Connection con = DriverManager.getConnection(connectInfo.m_DSN,
                    connectInfo.m_UID, connectInfo.m_PWD);
            
            DatabaseMetaData dbMetaData = con.getMetaData();
            
            ResultSet rsTables = dbMetaData.getTables(databaseSelected,null,null,tableTypes);
            boolean bMore = rsTables.next();
            while (bMore) {
                String strTableName = rsTables.getString("TABLE_NAME");
                
                // Determine the table type
                String tableTypeStr = rsTables.getString("TABLE_TYPE");
                int tableType;
                if (tableTypeStr.compareToIgnoreCase("SYSTEM TABLE") == 0)
                    tableType = TreeNodeInfo.TABLE_SYSTEM;
                else if (tableTypeStr.compareToIgnoreCase("TABLE") == 0)
                    tableType = TreeNodeInfo.TABLE;
                else if (tableTypeStr.compareToIgnoreCase("VIEW") == 0)
                    tableType = TreeNodeInfo.TABLE_VIEW;
                else
                    tableType = TreeNodeInfo.TABLE_OTHER;
                
                // Get primary keys
                Vector primaryKeys = new Vector();
                if (dsInfo.m_supportsCoreSQLGrammar) {
                    ResultSet rs = dbMetaData.getPrimaryKeys(databaseSelected,null,strTableName);
                    boolean more = rs.next();
                    while (more) {
                        primaryKeys.add(rs.getString("COLUMN_NAME"));
                        more = rs.next();
                    }
                    rs.close();
                }
                
                //add the table to the tree
                TreeNodeInfo nodeInfo = new TreeNodeInfo(strTableName,tableType);
                DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(nodeInfo);
                treeModel.insertNodeInto(childNode, rootNode, rootNode.getChildCount());
                treeTables.scrollPathToVisible(new TreePath(childNode.getPath()));
                ResultSet rsColumns = dbMetaData.getColumns(databaseSelected,null,strTableName,null);
                
                //determine the data types of each column
                boolean bMore2 = rsColumns.next();
                while (bMore2) {
                    String strColumnName = rsColumns.getString("COLUMN_NAME");
                    String strTypeName = rsColumns.getString("TYPE_NAME");
                    int sqlType = rsColumns.getShort("DATA_TYPE");
                    ValueType protegeType = Global.getSQLProtegeType(sqlType);
                    String nodeText = strColumnName+" ("+strTypeName+" --> "+protegeType.toString()+")";
                    
                    // Determine whether this column is a primary key
                    int colType = TreeNodeInfo.COLUMN;
                    for (int i = 0; i < primaryKeys.size(); i++) {
                        String key = (String)primaryKeys.elementAt(i);
                        if (key.compareToIgnoreCase(strColumnName) == 0) {
                            colType = TreeNodeInfo.COLUMN_PK;
                            break;
                        }
                    }
                    
                    //add each column to the tree under the table it belongs
                    TreeNodeInfo nodeInfo2 = new TreeNodeInfo(nodeText,colType);
                    DefaultMutableTreeNode childColumnNode = new DefaultMutableTreeNode(nodeInfo2);
                    treeModel.insertNodeInto(childColumnNode, childNode, childNode.getChildCount());
                    
                    bMore2 = rsColumns.next();
                }
                rsColumns.close();
                
                tables.add(nodeInfo);
                
                bMore = rsTables.next();
            }
            
            rsTables.close();
            con.close();
            
            if (tables.size() == 0) {
                JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(this),"No table of the selected types above found.",Global.tabName,JOptionPane.INFORMATION_MESSAGE);
            }
            
        } catch (SQLException ex) {
            Global.defaultSQLExceptionHandler(JOptionPane.getFrameForComponent(this),ex);
            
        } catch (Exception ex) {
        }
    }
    
    // This method is used to enable/disable the GUI components based
    // on the current state of the tab widget
    
    private void setConnectedGUI(boolean isConnected) {
        connected = isConnected;
        
        allCheckBox.setEnabled(isConnected);
        sysCheckBox.setEnabled(isConnected);
        tableCheckBox.setEnabled(isConnected);
        viewCheckBox.setEnabled(isConnected);
        otherCheckBox.setEnabled(isConnected);
        
        if (!isConnected) {
            allCheckBox.setSelected(isConnected);
            sysCheckBox.setSelected(isConnected);
            tableCheckBox.setSelected(isConnected);
            viewCheckBox.setSelected(isConnected);
            otherCheckBox.setSelected(isConnected);
        }
        
    }
    
    // A new table has been selected from the tree and we want to display
    // a preview of it in the preview table
    
    public void valueChanged(TreeSelectionEvent e) {
        //to check whether the tree corresponds to the currently working database
        if (treeModel.getChildCount(treeModel.getRoot())!=0){
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)treeTables.getLastSelectedPathComponent();
            if (node!=null){
                    DefaultMutableTreeNode parentNode=(DefaultMutableTreeNode)node.getParent();
                    TreeNodeInfo parentName=(TreeNodeInfo)parentNode.getUserObject();
                    if (parentName.toString().equals("Data Source")){
                        TreeNodeInfo nodeInfo = (TreeNodeInfo)node.getUserObject();
                        String strTableName = getDBMSSpecificNamingStyle(nodeInfo.m_text);
                
                        String strQuery = "SELECT * FROM " + strTableName;
                        previewPanel.updateTable(connectInfo,strQuery,databaseSelected);
                    }
            }
            if (node == null)
                return;
        }
    }
    
    
    // Different DBMS handle table names in queries differently.
    // For instance, MySQL does not allow characters such as spaces,
    // $, #, ', and other in table names while they are valid in DBMS such as
    // MS Access and Excel.  Therefore, this method is intended to modify the
    // table names accordingly to work with these different DBMS.
    
    private String getDBMSSpecificNamingStyle(String tableName) {
        if (tableName.indexOf(' ') != -1
                || tableName.indexOf('$') != -1
                || tableName.indexOf('#') != -1
                || tableName.indexOf('\'') != -1)
            return "\"" + tableName + "\"";
        else
            return tableName;
    }
    
    
    
    
    private JCheckBox allCheckBox, sysCheckBox, tableCheckBox, viewCheckBox, otherCheckBox;
    private String[] tableTypes;
    
    private Vector tables;
    
    private String strDriver;
    
    String databaseSelected;
    
    private JComboBox cmbDB;
    private JTextField txtHostIP = new JTextField("127.0.0.1",7);
    private JTextField txtPort = new JTextField("3306",4);
    private JTextField txtUserID = new JTextField(7);
    private JPasswordField txtPW = new JPasswordField(7);
    private JButton btnConnect = new JButton("Connect");
    private JButton btnGo = new JButton("Go!");
    QueryPanelMySQL queryPanel ;
    OntologyPanel ontPanel;
    Connection con;
    
    Vector primaryKeys = new Vector();
    Vector foreignKeys = new Vector();
    DragSource dragSource=new DragSource();
    
    private boolean connected = false;
    
    private ConnectInfo connectInfo = null;
    
    private DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new TreeNodeInfo("Data Source",TreeNodeInfo.OTHER));
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    JTree treeTables = new JTree(treeModel);
    
    private DataPreviewPanel previewPanel;
    private DataSourceInfo dsInfo;
}



